<template>
    <div class="search-result" ref="result">
        <scroll
            ref="list"
            class="scroll"
            :data="result"
            v-if="result.length"
            :pullup="pullup"
            @scrollToEnd="searchMore"
            :beforeScroll=beforeScroll
            @beforeScroll="listScroll"
        >
            <div class="content" ref="resultContent">
                <song-list
                    :songs="result"
                    @select="selectItem"
                    @clickIcon="showSongMenu"
                    :rank="rank"
                    :needPlayAll="needPlayAll"
                >
                </song-list>
                <div class="pull-up" v-show="hasMore" ref="pullUp">
                    <p class="pull-up-msg" v-show="!isPullUp">
                        上拉加载更多
                    </p>
                    <img class="load-icon"
                         v-show="isPullUp"
                         width="25"
                         hight="25"
                         src="./loading.gif"
                    >
                </div>
            </div>
        </scroll>
        <div class="load-wp" v-else>
            <load :isError="isLoadErr" @loadRefresh="reLoad"></load>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import Scroll from 'base/scroll/scroll'
    import SongList from 'base/song-list/song-list'
    import { mapActions, mapMutations, mapGetters } from 'vuex'
    import PlayListMixin from 'common/mixins/play-list'
    import SearchBoxMixin from 'common/mixins/search-box'
    import { MINI_PLAYER_HEIGHT } from 'common/js/config'
    import { getStyle } from 'common/js/dom'
    import Load from 'base/load/load'
    import { search } from 'api/search'
    import { ERR_OK } from 'api/config'
    import { createSong, isValidMusic, processSongsUrl } from 'common/js/classes/song'

    const perpage = 20

    export default {
        name: 'search-result',
        mixins: [PlayListMixin, SearchBoxMixin],
        data() {
            return {
                page: 1,
                pullup: true,
                beforeScroll: true,
                hasMore: true,
                result: [],
                rank: false,
                needPlayAll: false,
                isLoadErr: false,
                isPullUp: false,
                isFirstLoad: true
            }
        },
        props: {
            searchKey: {
                type: String,
                default: ''
            },
            showSinger: {
                type: Boolean,
                default: false
            }
        },
        created() {
            if (this.searchKey) {
                this._getSongList()
            }
        },
        computed: {
            ...mapGetters([
                'palyList'
            ])
        },
        methods: {
            _getSongList() {
                search(this.searchKey, this.page, this.showSinger, perpage).then((res) => {
                    if (res.code === ERR_OK) {
                        this._genResult(res.data)
                        this._checkMore(res.data)
                    }
                })
            },
            _genResult(data) {
                let ret = []
                // 处理歌手
                // if (data.zhida && data.zhida.singerid && this.page === 1) {
                //     ret.push({...data.zhida, ...{type: TYPE_SINGER}})
                // }
                return processSongsUrl(this._normalizeSongs(data.song.list)).then((songs) => {
                    ret = ret.concat(songs)
                    this.loadSuccess(ret)
                }).catch((msg) => {
                    console.log(msg)
                    this.loadErr()
                })
            },
            _normalizeSongs(list) {
                let ret = []
                list.forEach((musicData) => {
                    if (isValidMusic(musicData)) {
                        ret.push(createSong(musicData))
                    }
                })
                return ret
            },
            // 检查是否后端还有更多搜索结果
            _checkMore(data) {
                const song = data.song
                if (!song.list.length || (song.curnum + (song.curpage - 1) * perpage) >= song.totalnum) {
                    this.hasMore = false
                }
            },
            loadSuccess(result) {
                this.isPullUp = false
                this.page++
                if (!this.isFirstLoad) {
                    this.result = this.result.concat(result)
                    return
                }
                this.result = result
                this.$nextTick(() => {
                    this.handlePlayList(this.playList)
                })
                this.isFirstLoad = false
            },
            loadErr() {
                if (this.isFirstLoad) {
                    this.isLoadErr = true
                }
                this.isPullUp = false
            },
            reLoad() {
                this.isLoadErr = false
                this._getSongList()
            },
            searchMore() {
                this.isPullUp = true
                this._getSongList()
            },
            selectItem(item, index) {
                this.selectPlay({
                    list: this.result,
                    index: index
                })
            },
            showSongMenu(song) {
                this.setMenuSong(song)
            },
            // 重设滚动部分底部距离
            handlePlayList(playList) {
                if (!this.$refs.pullUp) {
                    return
                }
                const bottom = playList.length > 0 ? `${MINI_PLAYER_HEIGHT + 30}px` : ''
                const el = this.$refs.pullUp
                getStyle(el, 'paddingBottom', bottom)
                this.$refs.list.refresh()
            },
            ...mapActions([
                'selectPlay'
            ]),
            ...mapMutations({
                setMenuSong: 'SET_MENU_SONG'
            })
        },
        components: {
            SongList,
            Scroll,
            Load
        }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import "~common/stylus/variable"
    @import "~common/stylus/mixin"

    .search-result
        position: fixed
        top: $height-header
        bottom: 0
        left: 0
        right: 0
        overflow: hidden
        .scroll
            height: 100%
            width: 100%
            overflow: hidden
            .pull-up
                width: 100%
                padding-bottom: 30px
                .pull-up-msg
                    display: block
                    position: relative
                    width: 100px
                    margin: 0 auto
                    text-align: center
                    font-size: $font-size-small
                    color: $color-text-d
                    &::before, &::after
                        content: ''
                        display: block
                        position: absolute
                        width: 30px
                        border-top: 1px solid $color-text-d
                        top: 45%
                    &::before
                        left: -30px
                    &::after
                        right: -30px
                .load-icon
                    display: block
                    margin: 0 auto
        .load-wp
            position: fixed
            top: 40%
            width: 100%
            transform: translate3d(0, 50%, 0)
</style>
